import React, {Component} from 'react';
import {hashHistory,Link} from 'react-router';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Menu, Icon } from 'antd';
import createHistory from 'history/createBrowserHistory'

const SubMenu = Menu.SubMenu;
const history = createHistory();

class SiderMenu extends React.Component {
  constructor(props){
    super(props);
    this.rootSubmenuKeys = [];
    this.state = {
      openKeys: [],
      data: null,
      selectedKey: ''
    };
  }

  componentDidMount = () => {
    let hash = history.location.hash;
    let key = hash.slice(1);
    // console.log("key",key)
    this.setState({ selectedKey: key})

  }

  componentWillReceiveProps = (nextProps) => {
    // console.log("next",nextProps)
    let _data = nextProps.currentMenu;
    this.setState({ data: _data })
    
  }

  componentWillUnmount = () => {
		this.setState = (state,callback)=>{
          return;
        };
	}
  //点击菜单展开你
  onOpenChange = (openKeys) => {
    // console.log("当前点击的key",openKeys)
    const latestOpenKey = openKeys.find(key => this.state.openKeys.indexOf(key) === -1);
    // console.log("最后一次点击的key",latestOpenKey)
    if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      this.setState({ openKeys });
    } else {
      this.setState({
        openKeys: latestOpenKey ? [latestOpenKey] : [],
      });
    }
  }
  //点击选中
  handleClick = (e) => {
    this.setState({ selectedKey: e.key })
  }

  render() {
    if(this.state.data){
      let menu = this.state.data.sub;
      
      //控制左侧一级菜单的展开与合并，同一级只能展开一个（不包含二级菜单）
      for(let i in menu){
        if(menu[i].sub && this.rootSubmenuKeys.indexOf(menu[i].key) === -1){
          this.rootSubmenuKeys.push(menu[i].key)
        }
      }

      let _menu = data => data.map((item)=>{
          if(item.sub){
              return (
                  <SubMenu key={item.key} title={<span>{item.text}</span>}>
                      {_menu(item.sub)}
                  </SubMenu>
              )
          }else{
              return  <Menu.Item key={item.key}><Link to={item.url}>{item.text}</Link></Menu.Item> 
          }
      })
      return (
        <Menu
          mode="inline"
          // theme="dark"
          openKeys={this.state.openKeys}
          selectedKeys={[this.state.selectedKey]}
          onOpenChange={this.onOpenChange}
          onClick={this.handleClick}
        >
          {_menu(menu)}
        </Menu>
      );
    }else{
      return (
        <div></div>
      )
    }
  }
}

SiderMenu.PropTypes = {
  currentMenu: PropTypes.object.isRequired
}

export default connect()(SiderMenu);